package com.example.hs.Service;

import com.example.hs.DTO.OrderDTO;
import com.example.hs.Pojo.Order;
import com.example.hs.Pojo.User;
import com.example.hs.Pojo.Recycler;
import com.example.hs.Pojo.Category;
import com.example.hs.Repository.CategoryRepository;
import com.example.hs.Repository.OrderRepository;
import com.example.hs.Repository.RecyclerRepository;
import com.example.hs.Repository.UserRepository;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class OrderService {

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RecyclerRepository recyclerRepository;

    @Autowired
    private CategoryRepository categoryRepository;

    /**
     * 创建订单
     *
     * @param orderDTO 前端传递的订单数据
     * @return 创建的订单实体
     */
    public Order createOrder(OrderDTO orderDTO, HttpSession session) {
        // 从 session 中获取当前登录用户的 user_id
        User currentUser = (User)session.getAttribute("user");

        // 根据 recyclerId 查找回收员
        Recycler recycler = recyclerRepository.findById(orderDTO.getRecyclerId())
                .orElseThrow(() -> new RuntimeException("回收员不存在"));

        // 根据 categoryId 查找分类
        Category category = categoryRepository.findById(orderDTO.getCategoryId())
                .orElseThrow(() -> new RuntimeException("分类不存在"));

        // 创建 Order 实体
        Order order = new Order();
        order.setUser(currentUser);
        order.setRecycler(recycler);
        order.setCategory(category);
        order.setAddress(orderDTO.getAddress());
        order.setWeight(orderDTO.getWeight());
        order.setPrice(orderDTO.getPrice());
        order.setIphone(orderDTO.getIphone());
        order.setReTime(orderDTO.getReTime());
        order.setCreateTime(LocalDateTime.now());
        order.setStatus(0);

        // 保存订单到数据库
        return orderRepository.save(order);
    }

    /**
     * 根据 user_id 查询订单（不分页）
     *
     * @param userId 用户 ID
     * @return 订单列表
     */
    public List<Order> getOrdersByUserId(int userId) {
        return orderRepository.findByUser_userId(userId);
    }

    /**
     * 根据 recycler_id 查询订单（不分页）
     *
     * @param recyclerId 回收员 ID
     * @return 订单列表
     */
    public List<Order> getOrdersByRecyclerId(int recyclerId) {
        return orderRepository.findByRecycler_recyclerId(recyclerId);
    }

    public String deleteOrderById(int orderId) {
        if (orderRepository.existsById(orderId)) {
            orderRepository.deleteById(orderId);
            return "delete successful!";
        } else {
            return "order unexists!";
        }
    }


    public String updateOrderStatusById(int orderId) {
        Order order = orderRepository.findById(orderId).orElse(null);
        if (order != null&&order.getStatus()==0) {
            order.setStatus(1);
            orderRepository.save(order);
            return "update successful!";
        }
        else {
            return "order unexists!";
        }
    }

    public String updateOrderStatusById2(int orderId) {
        Order order = orderRepository.findById(orderId).orElse(null);
        if (order != null&&order.getStatus()==1) {
            order.setStatus(2);
            orderRepository.save(order);
            return "update successful!";
        }
        else {
            return "order unexists!";
        }
    }

    public String updateOrderStatusById3(int orderId) {
        Order order = orderRepository.findById(orderId).orElse(null);
        if (order != null&&order.getStatus()==0) {
            order.setStatus(3);
            orderRepository.save(order);
            return "update successful!";
        }
        else {
            return "order unexists!";
        }
    }

    public Order updateOrder(int orderId, Order updatedOrder) {
       return orderRepository.findById(orderId)
                .map(order -> {
                    order.setWeight(updatedOrder.getWeight());
                    order.setPrice(updatedOrder.getPrice());
                    return orderRepository.save(order);
                })
                .orElseThrow(() -> new RuntimeException("Order not found"));
    }

    public Order getOrderById(int orderId) {
        return orderRepository.findById(orderId).orElse(null);
    }
}